<template>
  <div>
    <Modal v-model="modal.show" width="40" :mask-closable="false" class="register-modal" footer-hide>
        <div class="register-box-top">
            <h1>{{modal.title}}</h1>
        </div>
        <div class="register-input register">
            <Form ref="registerForm" :model="registerForm" :rules="enterrules" class="register-form">
              <FormItem prop="email">
                <Input class="user" v-model="registerForm.email" size="large" :placeholder="$t('请输入邮箱')">
                </Input>
              </FormItem>
              <FormItem prop="code" class="yanzhengma" style="display:flex;" ref="captcha">
             
                  <Input class="verify" v-model="registerForm.code" size="large"
                         :placeholder="$t('Verificationcode')">
                  </Input>
                  <div style="flex:0 0 104px;float: right;text-align: right;" @click="sendCode">
                    <Tooltip :content="$t('发送后邮箱查收验证码')" placement="top" theme="dark">
                      <span  class="check-wrapper" v-if="sendtext.includes('邮箱验证码')">{{sendtext}}</span>
                      <span  class="check-wrapper" v-else style="border: 0;cursor: none">{{sendtext}}</span>
                    </Tooltip>
                  </div>
                


              </FormItem>
                <FormItem prop="username">
                    <Input class="user" v-model="registerForm.username" size="large" :placeholder="$t('enterusername')">
                    </Input>
                </FormItem>
              <FormItem prop="nickname">
                <Input class="user" v-model="registerForm.nickname" size="large" :placeholder="$t('请输入昵称')">
                </Input>
              </FormItem>
              
                <FormItem prop="password">
                    <Input class="pass" :type="!passType ? 'password' : 'text'" password v-model="registerForm.password"
                        size="large" :placeholder="$t('enterpassword')" autocomplete="new-password">
                    <div slot="suffix" @click="setPassType">
                        <Icon type="ios-eye-outline" v-if="passType" />
                        <Icon type="ios-eye-off-outline" v-else />
                    </div>
                    </Input>
                </FormItem>


<!--                <FormItem prop="type">-->
<!--                  <Select filterable disabled-->
<!--                      v-model="registerForm.type"-->
<!--                      placeholder="select"-->
<!--                  >-->
<!--&lt;!&ndash;                    <Option value="designer">单位设计师</Option>&ndash;&gt;-->
<!--&lt;!&ndash;                    <Option value="referee">裁判人员</Option>&ndash;&gt;-->
<!--                    <Option value="experimenter">操作员</Option>-->
<!--                  </Select>-->
<!--                </FormItem>-->

              <FormItem prop="userAgreement">
                <div class="check-wrapper" style="border: 0">
                  <div>
                    <Checkbox v-model="registerForm.userAgreement"></Checkbox>
                    <span @click="registerForm.userAgreement=!registerForm.userAgreement">我已阅读并接受</span>
                    <span style="text-decoration: underline" @click="showAgreement">{{$t('用户许可协议及隐私政策')}}</span>
                  </div>
                  <!-- <span v-if="readMeCopy">
                      <Checkbox v-model="readMeCopy" disabled></Checkbox>我已阅读并同意
                  </span><span class="text" @click="agreementModel = true">《奇安信隐私政策声明》</span> -->
                </div>
              </FormItem>
              
                <FormItem class="submit">

                  <Tooltip :content="$t('请先阅读并接受用户协议')" placement="top" theme="dark" v-if="!registerForm.userAgreement" transfer style="width: 100%;">
                    <Button class="register-btn" type="primary" long size="large" :loading="registerLoading" disabled 
                        @click="registerButton('registerForm')">
                        {{ $t('注册') }}
                    </Button>
                  </Tooltip>
                  <Button class="register-btn" type="primary" long size="large" :loading="registerLoading" v-else
                          @click="registerButton('registerForm')">{{ $t('注册') }}</Button>

                    <Button class="return-btn" type="primary" long style="background: #1D252C00 !important;color:#1D252C !important; " size="large" :loading="registerLoading"
                            @click="changeForm('login')">{{ $t('返回登录') }}</Button>
                </FormItem>
            </Form>
        </div>

    </Modal>

    <Modal
        v-model="agreementModel"
        title="用户许可协议及隐私政策"
        :closable="false"
        :mask-closable="false"
        :width="800"
        footer-hide
    >
      <article class="argument-wrapper">
        <header class="argument-header">
          <p>用户许可协议及隐私政策</p>
          <p>用户许可协议</p>
        </header>
        <section v-html="argumentContent" class="argument-content"></section>
        <footer class="argument-footer-wrapper">
          <div class="check-wrapper">
            <Checkbox v-model="registerForm.userAgreement" :disabled="readMeCopy"></Checkbox>
            我已阅读并同意《平台用户许可协议》
          </div>
          <Button class="comfirm-btn" :disabled="!registerForm.userAgreement" @click="read">确定</Button>
        </footer>
      </article>
    </Modal>
    
  </div>
</template>

<script>
    import encryption from '@/libs/encryption.js';
    import cookieUse from '@/libs/cookie.js';
    // import { register, verCode} from '@/api/login.js';
    import {sendCode,register} from "../../api/user";
    import { mapState,mapActions } from 'vuex';
    import {debounce} from '@/libs/utils'
    import argument from './argument_reg';
    export default {
        name: 'register',
        props:['changeForm'],
        mixins: [argument],
        data() {

            let regUsername = /^[0-9A-Za-z_]{5,18}$/; // 账号是数字 字母 或者下划线的组合
            let regPasswd = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}$/; // 密码必须包含大小写字母、数字和特殊字符，长度为8-16
            const validateUsername = (rule, value, callback) => {
              if (regUsername.test(value)) {
                callback();
              } else {
                callback(new Error('请输入长度为5-18位的账号,可以使用数字、字母或者下划线'));
              }
            };
            const validatePass = (rule, value, callback) => {
              if (regPasswd.test(value)) {
                callback();
              } else {
                callback(new Error('密码必须包含大写字母，小写字母，数字和特殊字符，长度为8-16位'));
              }
            };
            const validateNickname = (rule, value, callback) => {
              let reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,32}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error('请输入长度为1-32位的昵称,可以使用数字、中英文或者下划线'));
              }
            };
            const validateMobile = (rule, value, callback) => {
              let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
              if (value) {
                if (!myreg.test(value)) {
                  callback(new Error('请填写正确的手机号'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            };

            const validatEmail = (rule, value, callback) => {
              if (!this.validEmail(value)) {
                callback(new Error('请输入正确的邮箱地址'));
              } 
              callback();
              
            };
            return {
                formType:'register',
                modal: {
                    show: false,
                    title: '邮箱注册'
                },
                agreementModel:false,
                validate: {
                    user: true,
                    userPrompt: '',
                    pwd: true,
                    pwdPrompt: '',
                    yzm: true,
                    yzmPrompt: ''
                },
                remerberToken: true,
                registerLoading: false,
                // yzmPic: '',
                registerForm: {
                    userAgreement:false,
                    passwordInputType: 'password',
                    username: '',
                    password: '',
                    code: '',
                    companyId: '',//??
                    email: '',
                    nickname: '',
                    type: 'designer',
                },
                enterrules: {
                  
                    userAgreement: [
                      { required: true, type: 'boolean', message: '请阅读并勾选'},
                    ],
                    email: [
                      { required: true, type: 'string', message: '邮箱不能为空', trigger: 'change' },
                      { validator: validatEmail, trigger: 'blur' }
                    ],
                    nickname: [
                      { required: true, type: 'string', message: '昵称不能为空', trigger: 'change' },
                      { validator: validateNickname, trigger: 'blur' }
                    ],
                    code: [
                      { required: true, type: 'string', message: '验证码不能为空', trigger: 'change' },
                    ],
                    username: [
                        { required: true, type: 'string', message: '用户名不能为空', trigger: 'change' },
                        { validator: validateUsername, trigger: 'blur' }
                    ],
                    password: [{ required: true, type: 'string', message: '密码不能为空', trigger: 'change' },
                      { validator: validatePass, trigger: 'blur' }
                    
                    ]
                    // captcha: [{ required: true, type: 'string', message: '验证码不能为空', trigger: 'change' }]
                },
                // icon
                defYzm: require('../../assets/login/defYzm.png'),
                setDefYzm:(event) =>  {
                    let img = event.srcElement;
                    img.src = this.defYzm;
                    img.onerror = null;
                },
                //眼睛状态
                passType: false,
                sendtext:'发送邮箱验证码',
                sentTimout:-1,
                countdown:60,
                readMe: false,
                readMeCopy: false
            };
        },
        computed:{
            ...mapState('login',['t','key','salt','iv']),
            yzmPic(){
                if(this.t){
                    return `${this.baseURL}/identity/anonymity/captcha?t=${this.t}` 
                }else{
                    return this.defYzm
                }
            }
        },
        watch:{
            t(val){
                this.registerForm.captcha = '';
            }
        },
        mounted() {
            //绑定事件
            this._registerForm = {...this.registerForm};
            window.addEventListener('keydown', this.keyDown);
            this.verification();
        },
        destroyed() {
            window.removeEventListener('keydown', this.keyDown, false);
        },
        methods: {
            ...mapActions('login',['verification']),
            showAgreement(){
             // this.modal.show = false
              this.agreementModel = true
              
            },
            validEmail(email){
              var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

              return emailRegex.test(email);
            },
          
            sendCode(){
                let email = this.registerForm.email
                if(!email || (!this.validEmail(email))){
                  this.$Message.warning('请输入正确的邮箱地址')
                  return
                }

                if(this.sendtext!=='发送邮箱验证码'){
                  return;
                }

                sendCode(this.registerForm.email).then(res=>{
                   if (res.data.code === 1) {
                      this.sendCodeSuc()
                      this.$Message.success('发送成功，请到邮箱查收验证码')
                   }else {
                      this.$Message.warning(res.data.message)
                   }
                })
            },
            sendCodeSuc(){
              // 设置倒计时
              this.sentTimout = setInterval(()=>{
                this.countdown--;
                
                this.sendtext = this.countdown + ' 秒后重新发送';

                if (this.countdown <= 0) {
                  clearInterval(this.sentTimout);
                  this.countdown = 60;
                  this.sendtext = '发送邮箱验证码';
                }
              }, 1000);
            },
          
            resetFormItem(formRef,prop){
                this.$refs[formRef].fields.forEach(function (e) {
                    if (e.prop === prop) {
                        e.resetField()
                    }
                })
            },
            openModal(){
                // 验证码
                this.verification();
                this.modal.show = true;
                this.registerForm = {...this._registerForm};
                this.$refs.registerForm.resetFields();
            },
            closeModal(){
              this.modal.show = false;
            },

            getVerification(){
                !this.registerLoading && this.verification()
            },
            setPassType() {
                this.passType = !this.passType;
            },
            // 点击显示密码
            showPassword() {
                if (this.registerForm.passwordInputType === 'text') {
                    this.registerForm.passwordInputType = 'password';
                } else {
                    this.registerForm.passwordInputType = 'text';
                }
            },
            // 用户注册
            keyDown(e) {
                //如果是回车则执行注册方法
                if (e.keyCode == 13) {
                    this.registerButton();
                }
            },
            trimStr(str) {
              return str.replace(/(^\s*)|(\s*$)/g, '');
            },
            // 注册
            registerButton:debounce(function() {
                
                let _this = this;
              
                this.$refs['registerForm'].validate((valid) => {
                    if (valid) {
                        let params = {
                            username: this.trimStr(this.registerForm.username),
                            nickname: this.trimStr(this.registerForm.nickname),
                        };
                        let data = Object.assign({},this.registerForm,params)

                        this.registerLoading = true
                        register(data).then((res) => {
                                this.registerLoading = false
                                if (res.data.code === 1) {
                                    let token = res.data.data;
                                    this.$Message.success({
                                      content: '注册成功,返回登录',
                                      duration: 3
                                    });
                                    setTimeout(()=>{
                                      this.changeForm('login')
                                    },3000)
                                } else {
                                    this.$Message.error({
                                        content: res.data.message,
                                        duration: 3
                                    });
                                }
                            })
                            .catch((err) => {
                              this.registerLoading = false
                              this.$Message.error({
                                content: err,
                                duration: 3
                              });
                            });
                    } else {
              
                    }
                });
            },500),
            // 切换语言
            // changeLang(){
            //     let val = ''
            //     if(this.langText === '中文'){
            //         val = 'zh'
            //         this.langText = 'English'
            //     }else {
            //         val = 'en'
            //         this.langText = '中文'
            //     }
            //     this.$i18n.locale = val
            //     cookieUse.setCookie('language-s',val)
            //     window.location.reload()
            // },
            read(){
              this.modal.show = true
              this.registerForm.userAgreement = true
              this.agreementModel = false
              
            },
          
            cancelModal() {
                this.agreementModel = false;
                this.readMeCopy = true;
            }
        },
    };
</script>

<style scoped>
    .return-btn{
      background: #1D252C00;
      margin-top: 20px;
      border: 1px solid #1D252C;
    }
    .register-modal /deep/ .ivu-modal-content {
        border-radius: 0;
        border-top: 2px solid #C81125;
        background: #fff;
    }

    .register-modal /deep/ .ivu-modal-body {
        padding: 12% 15%;
    }

    .register-box-top {
        /* padding: 20px 40px; */
        color: #C81125;
        margin-bottom: 30px;
    }

    .register-form {
        /* padding: 20px 40px; */
    }

    .register-form .check-wrapper {
        display: flex;
        font-weight: bold;
        align-items: center;
        line-height: 1;
        color:#1d252c;
        line-height: 20px;
        border-bottom: 1px solid #1d252c;
        letter-spacing:1px;
        cursor: pointer;
    }

    .register-form .check-wrapper span.text {
        color: #3669c3;
        margin-top: -2px;
        cursor: pointer;
    }

    /deep/ .register-input .ivu-input-suffix {
        height: 26px;
        margin-top: 12px;
    }

    /deep/ .register-input .pass .ivu-input-suffix i.ivu-icon-ios-eye-off-outline:before {
        content: '';
        display: block;
        width: 20px;
        height: 20px;
        background: url('../../assets/login-qax/icon_by.png') no-repeat;
    }

    /deep/ .register-input .pass .ivu-input-suffix i.ivu-icon-ios-eye-outline:before {
        content: '';
        display: block;
        width: 20px;
        height: 20px;
        background: url('../../assets/login-qax/icon_open.png') no-repeat;
    }
    .submit{
        margin-bottom:0;
    }
    /deep/ .submit button,.submit button:hover {
        height: 46px!important;
        background: #1D252C!important;
        border-radius: 0px!important;
    }

    /deep/ .register-input .ivu-input ,/deep/ .register-input .ivu-select{
        height: 48px;
        color: #1d252c !important;
        border-radius: 0px;
        background: #F7F9FB;
        border-radius: 0px 0px 0px 0px;
        border: 1px solid #EBEEF2;
    }

    /deep/ .register-input .ivu-input::-webkit-input-placeholder, /deep/ .register-input .ivu-select::-webkit-input-placeholder {
        color: #535D6D !important;
    }

    /deep/ .register-input .ivu-input:hover, /deep/ .register-input .ivu-select:hover{
        border: 1px solid #EBEEF2;
    }

    /deep/ .register-input .ivu-input:focus , /deep/ .register-input .ivu-select:focus{
        box-shadow: none !important;
        /*box-shadow:0px 0px 8px rgb(167, 153, 218);
        border: 1px solid rgb(167, 153, 218);
        color: rgb(167, 153, 218)!important;*/
    }

    /deep/ .register-input .ivu-form-item-error .ivu-input,/deep/ .register-input .ivu-form-item-error .ivu-select {
        border: 1px solid #ed4014;
    }

    /deep/ .register-input .ivu-form-item-error .ivu-input:focus,/deep/ .register-input .ivu-form-item-error .ivu-select:focus {
        /* border: 1px solid #ed4014; */
        box-shadow: 0px 0px 8px rgb(237, 64, 20, 0.6);
    }


    /deep/ .register-input .ivu-select-single .ivu-select-selection {
      height: 46px;
      position: relative;
      background: #f7f9fb;
      line-height: 46px;
      color: #535d6d;
      border: 0;
    }
    /deep/ .register-input .ivu-select-selected-value{
      line-height: 46px;
      color: black;
    }

    /deep/ .verify {
        flex: auto;
        margin-right: 10px;
    }

    /deep/ .yanzhengma .ivu-form-item-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
    }

    /deep/ .ivu-btn-primary {
        color: #fff !important;
    }

    .langWrap .ivu-btn-ghost.ivu-btn-dashed {
        color: rgba(255, 255, 255, 0.6);
        border-color: rgba(255, 255, 255, 0.6);
    }

    .langWrap .ivu-btn-ghost.ivu-btn-dashed:hover {
        color: #57a3f3;
        border-color: #57a3f3;
    }

    .register-btn {
      background: #1D252C;
    }


    .argument-wrapper {
        /*font-size:14px;*/
    }

    .argument-header {
        margin-bottom: 10px;
        font-size: 14px;
        text-align: center;
        font-weight: bold;
    }

    .argument-content {
        line-height: 1.5;
        height: 50vh;
        overflow: auto;
        font-size: 12px;
    }

    .argument-footer-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
    }

    .argument-footer-wrapper .check-wrapper {
        display: flex;
        color: #666666;
    }

    .comfirm-btn {
        background: #2e6be6;
        color: #fff;
    }

    .comfirm-btn:disabled {
        opacity: 0.3;
    }

    .comfirm-btn:disabled:hover {
        background: #2e6be6;
        color: #fff;
        opacity: 0.3;
    }

    .comfirm-btn {
        background: #2e6be6;
        color: #fff;
    }
</style>
<style>
    #register-page .register-input .ivu-input {
        color: #fff !important;
    }

    #register-page .register-input .ivu-input::-webkit-input-placeholder {
        color: rgba(255, 255, 255, 0.3) !important;
    }

    #register-page .ivu-checkbox-checked .ivu-checkbox-inner {
        border-color: transparent;
    }

    .argument-content p {
        margin: 10px 0;
    }

    .argument-content td {
        padding: 5px;
    }
</style>